/**
 * Copyright 2008 Adam Ruggles.
 * 
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 * 
 * http://www.apache.org/licenses/LICENSE-2.0
 * 
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package kiff.util.transaction;

import javax.naming.Context;
import javax.naming.NamingException;
import javax.transaction.UserTransaction;

import kiff.util.Provider;

import com.google.inject.Inject;
import com.google.inject.name.Named;

/**
 * JTA Transaction Wrapper Provider.
 * @author Adam
 * @version $Id: JtaTransactionProvider.java 62 2008-10-31 04:51:50Z a.ruggles $
 * 
 * Created on Oct 9, 2008 at 12:59:50 PM 
 */
public class JtaTransactionProvider implements Provider<Transaction> {
	/**
	 * The Default location for the JTA User Transaction.
	 */
	private static final String DEFAULT_USER_TRANSACTION_NAME = "java:comp/UserTransaction";

	/**
	 * The environment context.
	 */
	private final Context context;

	/**
	 * The location for the JTA UserTransaction.
	 */
	private final String userTransactionName;

	/**
	 * Constructs a JTA Transaction Provider.
	 * @param context The environment context.
	 * @param userTransactionName The location for the JTA UserTransaction.
	 */
	@Inject
	public JtaTransactionProvider(final Context context,
			@Named("env.userTransactionName") final String userTransactionName) {
		if (context == null) {
			throw new IllegalArgumentException("Environment Context cannot be null");
		}
		this.context = context;
		if (userTransactionName == null) {
			this.userTransactionName = DEFAULT_USER_TRANSACTION_NAME;
		} else {
			this.userTransactionName = userTransactionName;
		}
		try {
			UserTransaction utx = (UserTransaction) context.lookup(userTransactionName);
			if (utx == null) {
				throw new IllegalArgumentException("Invalid Location for the UserTransaction.");
			}
		} catch (NamingException e) {
			throw new IllegalArgumentException("Invalid User Transaction Name.", e);
		}
	}

	/**
	 * {@inheritDoc}
	 * @see kiff.util.Provider#get()
	 */
	public Transaction get() {
		try {
			UserTransaction utx = (UserTransaction) context.lookup(userTransactionName);
			return new JtaTransaction(utx);
		} catch (NamingException e) {
			throw new IllegalArgumentException("Invalid User Transaction Name.", e);
		}
	}
}
